package com.itqf.controller;

import com.itqf.pojo.Cart;
import com.itqf.pojo.User;
import com.itqf.service.CartService;
import com.itqf.service.impl.CartServiceImpl;
import com.itqf.utils.Constants;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 20:22
 * description:
 */
@WebServlet("/cart/*")
public class CartController extends BaseServlet {

     public String  save(HttpServletRequest request, HttpServletResponse response) throws SQLException {

         //1.获取参数
         String gId = request.getParameter("gId");
         String gPrice = request.getParameter("gPrice");

         //用户id
         User user = (User) request.getSession().getAttribute("user");

         if (user == null) {
             request.getSession().setAttribute("msg", "添加购物车必须要先登录!");
             return Constants.REDIRECT_ACTION + request.getContextPath() + "/login.jsp";
         }

         int uId = user.getuId();

         //2.添加购物车业务
         CartService cartService = new CartServiceImpl();
         cartService.save(gId,gPrice,uId);

         return Constants.FORWARD_ACTION + "/cartSuccess.jsp";
     }


    /**
     * 购物车展示功能
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String  show(HttpServletRequest request, HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {

        //1.用户id
        User user = (User) request.getSession().getAttribute("user");

        if (user == null) {
            request.getSession().setAttribute("msg", "添加购物车必须要先登录!");
            return Constants.REDIRECT_ACTION + request.getContextPath() + "/login.jsp";
        }

        //2.查询数据库购物车数据
        CartService cartService = new CartServiceImpl();
        List<Cart> cartList =  cartService.findAll(user.getuId());

        //3.响应数据
        request.setAttribute("cartList", cartList);

        return Constants.FORWARD_ACTION + "/cart.jsp";
    }


}
